<script setup lang="ts">
import useDialog from '@/hooks/useDialog.ts'
import SysDialog from '@/components/dialog/SysDialog.vue'
import SelectChecked from '@/components/selectChecked/SelectedChecked.vue'
import { ElMessage, FormInstance } from 'element-plus'
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  getParentApi,
  addApi,
  getListApi,
  editApi,
  deleteApi,
} from '@/api/productConfig/index.ts'
import { User } from '@/api/user/type.ts'
import { ProductConfig } from '@/api/productConfig/type.ts'
// 弹框属性
const { dialog, onShow, onClose, onConfirm } = useDialog()
import useInstance from '@/hooks/useInstance.ts'
import ElIconPicker from '@/components/iconPicker/ElIconPicker.vue'
// 导入图片上传组件
import ImageUpload from '@/components/ImageUpload/index.vue'
// 图标引入
import { Plus, Edit, Delete, Document, Setting, Picture, Grid, FolderOpened, Tools, Files, ArrowRight, Refresh } from '@element-plus/icons-vue'

// 获取全局 global
const { global } = useInstance()

// 表单ref属性
const addRef = ref<FormInstance>()
// 新增表单绑定对象
const addModel = reactive({
  id: undefined as number | undefined, // id
  parentId: undefined as number | undefined, // 上级id
  name: undefined as string | undefined, // 名称
  category: undefined as string | undefined, // 类型名称
  spec: undefined as string | undefined, // 型号
  model: undefined as string | undefined, // 规格
  thickness: undefined as number | undefined, // 厚度
  material: undefined as string | undefined, // 材质
  length: undefined as number | undefined, // 长度
  quantity: undefined as number | undefined, // 数量
  coefficient: undefined as number | undefined, // 系数
  process: undefined as string | undefined, // 工艺
  unitPrice: undefined as number | undefined, // 单价
  img:'', // 图片
})

// 表单校验规则
const rules = reactive({
  parentId: [{ required: true, message: '请选择上级配件', trigger: 'change' }],
  name: [{ required: true, message: '请输入配件名称', trigger: 'blur' }],
  category: [{ required: true, message: '请输入类别', trigger: 'blur' }],
  spec: [{ required: true, message: '请输入型号', trigger: 'blur' }],
  model: [{ required: true, message: '请输入规格', trigger: 'blur' }],
  thickness: [
    { required: true, message: '请输入厚度', trigger: 'blur' },
    { type: 'number', message: '厚度必须为数字', trigger: 'blur' },
  ],
  material: [{ required: true, message: '请输入材质', trigger: 'blur' }],
  length: [
    { required: true, message: '请输入长度', trigger: 'blur' },
    { type: 'number', message: '长度必须为数字', trigger: 'blur' },
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', message: '数量必须为数字', trigger: 'blur' },
  ],
  coefficient: [
    { required: true, message: '请输入系数', trigger: 'blur' },
    { type: 'number', message: '系数必须为数字', trigger: 'blur' },
  ],
  unitPrice: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { type: 'number', message: '单价必须为数字', trigger: 'blur' },
  ],
})

// 上级菜单数据
const treeList = ref([])
const getParent = async () => {
  try {
    const result = await getParentApi()
    treeList.value = result.data
  } catch (error) {
    console.log(error)
  }
}
// 上级下单选中事件
const treeClick = (item: any) => {
  //addModel.parentName = item.title
}

// 表格数据
const tableData = ref([])
// 新增按钮
const addBtn = () => {
  dialog.title = '新增配件'
  dialog.height = 450
  dialog.width = 800
  // 显示弹框
  onShow()
  // 获取上级菜单
  getParent()
  // 清理表单
  addRef.value?.resetFields()
  // 清空值
  Object.assign(addModel, {
    id: undefined as number | undefined, // id
    parentId: undefined as number | undefined, // 上级id
    name: undefined as string | undefined, // 名称
    category: undefined as string | undefined, // 类型名称
    spec: undefined as string | undefined, // 型号
    model: undefined as string | undefined, // 规格
    thickness: undefined as number | undefined, // 厚度
    material: undefined as string | undefined, // 材质
    length: undefined as number | undefined, // 长度
    quantity: undefined as number | undefined, // 数量
    coefficient: undefined as number | undefined, // 系数
    process: undefined as string | undefined, // 工艺
    unitPrice: undefined as number | undefined, // 单价
    img:'',
  })
}

// 表单提交
const commit = () => {
  addRef.value?.validate(async (valid) => {
    if (valid) {
      console.log('通过')
      try {
        console.log(addModel)
        // 提交请求
        if (!addModel.id) {
          const result = await addApi(addModel)
          ElMessage.success('新增配置成功')
        } else {
          const result = await editApi(addModel)
          ElMessage.success('修改配置成功')
        }
        // 刷新列表
        getList()
        //关闭弹框
        onClose()
      } catch (error) {}
    }
  })
}

// 获取表格数据
const getList = async () => {
  try {
    const result = await getListApi()
    tableData.value = result.data
  } catch (error) {
    console.log(error)
  }
}

// 编辑按钮
const editBtn = async (row: ProductConfig) => {
  console.log(row)
  // 显示弹框
  dialog.title = '编辑配件'
  dialog.height = 450
  dialog.width = 800
  // 显示弹框
  onShow()
  // 清理表单
  addRef.value?.resetFields()
  // 获取上级菜单
  getParent()
  // 回显数据
  Object.assign(addModel, row)
}
// 删除按钮
const deleteBtn = async (id: number) => {
  const confirm = await global.$myConfirm('此操作将永久删除该配置，是否继续?')
  if (confirm) {
    try {
      const result = await deleteApi(id)
      ElMessage.success('删除成功')
      // 刷新列表
      getList()
    } catch (error) {
      console.log(error)
    }
  }
}

// 表格高度
const tableHeight = ref()

onMounted(() => {
  getList()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
})

// 定义加载状态
const loading = ref(false)
</script>

<template>
  <el-main class="product-config-main">
    <div class="main-container">
      <!-- 工具栏区域 -->
      <el-card class="toolbar-card" shadow="hover">
        <div class="toolbar">
          <div class="left-tools">
            <h2 class="page-title"><el-icon><Grid /></el-icon> 产品配件管理</h2>
          </div>
          <div class="right-tools">
            <el-button type="success" class="add-btn" :icon="Plus" @click="addBtn" v-permission="['sys:menu:add']">
              新增配件
            </el-button>
            <el-button class="refresh-btn" :icon="Refresh" @click="getList">
              刷新
            </el-button>
          </div>
        </div>
      </el-card>
      
      <!-- 表格区域 -->
      <el-card class="table-card" shadow="hover">
        <el-table 
          v-loading="loading"
          :height="tableHeight"
          :data="tableData"
          border
          stripe
          row-key="id"
          default-expand-all
          class="data-table"
          highlight-current-row
        >
          <el-table-column prop="name" label="配件名称" min-width="160" fixed="left" align="center" />
          <el-table-column prop="category" label="类别" min-width="100" fixed="left" align="center" />
          <el-table-column prop="spec" label="型号" min-width="120" fixed="left" align="center" />
          <el-table-column prop="model" label="规格" min-width="100" fixed="left" align="center" />
          <el-table-column prop="thickness" label="厚度" min-width="100" fixed="left" align="center" />
          <el-table-column prop="material" label="材质" min-width="100" fixed="left" align="center" />
          <el-table-column prop="length" label="长度" min-width="100" align="center" />
          <el-table-column prop="quantity" label="数量" min-width="100" align="center" />
          <el-table-column prop="coefficient" label="系数" min-width="100" align="center" />
          <el-table-column prop="process" label="工艺" min-width="100" align="center" />
          <el-table-column prop="unitPrice" label="单价" min-width="100" align="center" />

          <el-table-column prop="map.单面积" label="单面积(m²/个)" min-width="100" align="center" />
          <el-table-column prop="map.单重" label="单重(kg/件)" min-width="100" align="center" />
          <el-table-column prop="map.总面积" label="总面积(m²/个)" min-width="100" align="center" />
          <el-table-column prop="map.总重" label="总重(kg/件)" min-width="100" align="center" />
          <el-table-column prop="map.单费用" label="标准单价(元/件)" min-width="100" align="center" />
          <el-table-column prop="map.材料费用" label="材料费用(元/件)" min-width="100" align="center" />
          <el-table-column prop="map.工艺费用" label="工艺费用(元/件)" min-width="100" align="center" />
          <el-table-column prop="map.单价索取系数" label="单价索取系数" min-width="100" align="center" />
          <el-table-column prop="map.材料索取系数" label="材料索取系数" min-width="100" align="center" />
          <el-table-column prop="map.标准单价" label="标准单价(元/kg)" min-width="100" align="center" />
          <el-table-column prop="map.工艺单价" label="工艺单价(元/kg)" min-width="100" align="center" />
          <el-table-column prop="map.自动冲压@单价" label="自动冲压单价" min-width="100" align="center" />
          <el-table-column prop="map.自动冲压@总价" label="自动冲压费用" min-width="100" class-name="highlight-column" align="center" />
          <el-table-column prop="map.辊轧成型@单价" label="辊轧成型单价" min-width="100" align="center" />
          <el-table-column prop="map.辊轧成型@总价" label="辊轧成型费用" min-width="100" align="center" />
          <el-table-column prop="map.切管下料@单价" label="切管下料单价" min-width="100" align="center" />
          <el-table-column prop="map.切管下料@总价" label="切管下料费用" min-width="100" align="center" />
          <el-table-column prop="map.激光下料@单价" label="激光下料单价" min-width="100" align="center" />
          <el-table-column prop="map.激光下料@总价" label="激光下料费用" min-width="100" align="center" />
          <el-table-column prop="map.剪板下料@单价" label="剪板下料单价" min-width="100" align="center" />
          <el-table-column prop="map.剪板下料@总价" label="剪板下料费用" min-width="100" align="center" />
          <el-table-column prop="map.板材下料@单价" label="板材下料单价" min-width="100" align="center" />
          <el-table-column prop="map.板材下料@总价" label="板材下料费用" min-width="100" align="center" />
          <el-table-column prop="map.冲压@单价" label="冲压单价" min-width="100" align="center" />
          <el-table-column prop="map.冲压@总价" label="冲压费用" min-width="100" align="center" />
          <el-table-column prop="map.钻孔@单价" label="钻孔单价" min-width="100" align="center" />
          <el-table-column prop="map.钻孔@总价" label="钻孔费用" min-width="100" align="center" />
          <el-table-column prop="map.折弯@单价" label="折弯单价" min-width="100" align="center" />
          <el-table-column prop="map.折弯@总价" label="折弯费用" min-width="100" align="center" />
          <el-table-column prop="map.焊接@单价" label="焊接单价" min-width="100" align="center" />
          <el-table-column prop="map.焊接@总价" label="焊接费用" min-width="100" align="center" />
          <el-table-column prop="map.抛丸@单价" label="抛丸单价" min-width="100" align="center" />
          <el-table-column prop="map.抛丸@总价" label="抛丸费用" min-width="100" align="center" />
          <el-table-column prop="map.喷涂@单价" label="喷涂单价" min-width="100" align="center" />
          <el-table-column prop="map.喷涂@总价" label="喷涂费用" min-width="100" align="center" />

          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button type="primary" size="small" class="edit-btn" :icon="Edit" @click.prevent="editBtn(scope.row)" v-permission="['sys:menu:update']">
                  编辑
                </el-button>
                <el-button type="danger" size="small" class="delete-btn" :icon="Delete" @click.prevent="deleteBtn(scope.row.id)" v-permission="['sys:menu:delete']">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!--新增、编辑弹框-->
    <SysDialog 
      :title="dialog.title"
      :width="dialog.width"
      :height="dialog.height"
      :visible="dialog.visible"
      @on-close="onClose"
      @on-confirm="commit"
      custom-class="product-dialog"
    >
      <template v-slot:content>
        <el-form 
          :model="addModel"
          ref="addRef"
          :rules="rules"
          label-width="auto"
          class="product-form"
        >
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><FolderOpened /></el-icon>
                <span>配件基本信息</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="上级配件" prop="parentId">
                  <el-tree-select 
                    v-model="addModel.parentId"
                    :data="treeList"
                    :render-after-expand="false"
                    placeholder="请选择上级配件"
                    show-checkbox
                    check-strictly
                    node-key="id"
                    class="full-width"
                    :props="{
                      label: 'name',
                      value: 'id',
                      children: 'children'
                    }" 
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="配件名称" prop="name">
                  <el-input v-model="addModel.name" placeholder="请输入配件名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="类别" prop="category">
                  <el-input v-model="addModel.category" placeholder="请输入类别" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="型号" prop="spec">
                  <el-input v-model="addModel.spec" placeholder="请输入型号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="规格" prop="model">
                  <el-input v-model="addModel.model" placeholder="请输入规格" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><Tools /></el-icon>
                <span>配件详细参数</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="厚度" prop="thickness">
                  <el-input-number 
                    v-model="addModel.thickness"
                    :precision="2"
                    :step="0.1"
                    :controls="true"
                    class="full-width"
                    placeholder="请输入厚度" 
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="材质" prop="material">
                  <el-input v-model="addModel.material" placeholder="请输入材质" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="长度" prop="length">
                  <el-input-number 
                    v-model="addModel.length"
                    :precision="2"
                    :step="0.1"
                    :controls="true"
                    class="full-width"
                    placeholder="请输入长度" 
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="数量" prop="quantity">
                  <el-input-number 
                    v-model="addModel.quantity"
                    :precision="0"
                    :step="1"
                    :controls="true"
                    class="full-width"
                    placeholder="请输入数量" 
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="系数" prop="coefficient">
                  <el-input-number 
                    v-model="addModel.coefficient"
                    :precision="2"
                    :step="0.1"
                    :controls="true"
                    class="full-width"
                    placeholder="请输入系数" 
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工艺" prop="process">
                  <el-input v-model="addModel.process" placeholder="请输入工艺" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><Files /></el-icon>
                <span>价格与图片信息</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="单价" prop="unitPrice">
                  <el-input-number 
                    v-model="addModel.unitPrice"
                    :precision="2"
                    :step="0.1"
                    :controls="true"
                    class="full-width"
                    placeholder="请输入单价" 
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品图">
                  <image-upload 
                    v-model="addModel.img"
                    :limit="1"
                    :file-size="2"
                    :file-type="['jpg', 'png']"
                    class="image-uploader"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </template>
    </SysDialog>
  </el-main>
</template>

<style scoped lang="scss">
.product-config-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.toolbar-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .left-tools {
    .page-title {
      margin: 0;
      font-size: 18px;
      color: #67c23a;
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-icon {
        color: #67c23a;
      }
    }
  }
  
  .right-tools {
    display: flex;
    gap: 10px;
    
    .el-button {
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
    }
    
    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;
      
      &:hover {
        opacity: 0.9;
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 0;
  
  :deep(.el-card__body) {
    padding: 0;
  }
}

.data-table {
  border-radius: 4px;
  
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }
  
  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    gap: 10px;
    
    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
  }
  
  :deep(.highlight-column) {
    .cell {
      background-color: rgba(255, 230, 0, 0.2);
      font-weight: bold;
    }
  }
}

.product-form {
  padding: 20px;
  
  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }
    
    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-icon {
        color: #67c23a;
      }
    }
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
  
  :deep(.el-input__wrapper), :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #67c23a inset;
    }
  }
  
  .full-width {
    width: 100%;
  }
  
  .image-uploader {
    :deep(.el-upload--picture-card) {
      border-radius: 8px;
      border: 1px dashed #d9d9d9;
      
      &:hover {
        border-color: #67c23a;
      }
    }
  }
}

:deep(.product-dialog) {
  border-radius: 8px;
  overflow: hidden;
  
  .el-dialog__header {
    padding: 15px 20px;
    margin: 0;
    background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
    border-bottom: 1px solid #e1f3d8;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
    
    .el-dialog__headerbtn {
      top: 15px;
    }
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    padding: 10px 20px;
    border-top: 1px solid #ebeef5;
    background-color: #f5f7fa;
    
    .el-button {
      padding: 8px 20px;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}
</style>
